package codetop.microsoft.T1233;

import java.util.*;

/**
 * @Author: 18362
 * @Create: 2022-09-07 22:23:37 星期三
 */
class Solution {
    public List<String> removeSubfolders(String[] folder) {
        Arrays.sort(folder);
        int i = 0;
        List<String> res = new ArrayList<>();
        while (i < folder.length) {
            if (folder[i].equals("") || folder[i].equals("/"))
                continue;
            int j = i + 1;
            String base = folder[i];
            res.add(base);
            while (j < folder.length) {
                if (!judge(base, folder[j]))
                    break;
                j++;
            }
            i = j;
        }
        return res;
    }

    private boolean judge(String base, String target) {
        if (target.length() <= base.length())
            return false;
        int k = -1;
        for (int i=0; i<base.length(); ++i) {
            if (base.charAt(i) != target.charAt(i)) {
                k = i;
                break;
            }
        }
        if (k < 0 && target.charAt(base.length()) == '/')
            return true;
        return false;
    }
}